package com.example.fileupload;

import com.example.Constant;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * @author zhanghui
 * @date 2021/12/6 13:44
 */
public class FileUploadClient {
    public static void main(String[] args) throws IOException {
        FileUploadClient client = new FileUploadClient();
        client.uploadFile();
    }

    private Charset charset = Charset.forName("UTF-8");

    private void uploadFile() throws IOException {
        String sourceFileName = "nioClientFile.txt";
        String destFileName = "nioServerFile.txt";
        File file = new File(sourceFileName);
        if (!file.exists()) {
            System.out.println("文件不存在");
            return;
        }
        FileChannel fileChannel = new FileInputStream(file).getChannel();
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.socket().connect(new InetSocketAddress(Constant.SERVER_IP, Constant.SERVER_PORT));
        while (!socketChannel.finishConnect()) {

        }
        System.out.println("已连接服务器");

        // 发送文件名
        socketChannel.write(charset.encode(destFileName));

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 发送文件长度
        long fileLength = file.length();
        buffer.putLong(fileLength);
        buffer.flip();
        socketChannel.write(buffer);
        buffer.clear();

        System.out.println("开始传输文件");
        int readLength = 0;
        long progress = 0;
        while ((readLength = fileChannel.read(buffer)) > 0) {
            buffer.flip();
            socketChannel.write(buffer);
            buffer.clear();
            progress += readLength;
            System.out.println("| " + (100 * progress / fileLength) + "% |");
        }

        if (readLength == -1) {
            socketChannel.shutdownOutput();
            socketChannel.close();
            fileChannel.close();
            System.out.println("=======文件传输成功=======");
        }
    }
}
